<?php


namespace app\admin\controller;


use app\admin\validate\AttributeValidate;
use app\admin\validate\CategoryValidate;
use app\admin\validate\IDMustBePositiveInt;
use app\service\model\AttributeModel;
use app\service\model\CategoryModel;
use app\service\Tree;
use app\service\Y;
use think\Request;

class Attribute extends BaseAdmin
{

    /**
     * 管理员列表
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function index(Request $request): \think\response\Json
    {
        $datas = AttributeModel::select();
        return Y::table($datas, count($datas));
    }

    /**
     * 分类数据，根据分类等级格式化
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function attribute_level_format(): \think\response\Json
    {
        $datas = AttributeModel::where('pid', '=', 0)->select();
        return Y::success($datas, '数据');
    }

    /**
     * 创建、编辑分类
     * @param Request $request
     * @param CategoryValidate $category_validate
     * @return \think\response\Json
     * @throws \app\service\exception\ParameterException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function save(Request $request, AttributeValidate $attribute_validate): \think\response\Json
    {
        $id = input('param.id', 0);

        if ($request->isPost()) {
            $attribute_validate->goCheck();
            $param = $attribute_validate->getDataByRule();

            return AttributeModel::saveData($param, $id);
        }

        $data = [];
        if ($id > 0) {
            $data = AttributeModel::field('name, id, pid')->find($id);
        }
        return Y::success($data, '属性数据');
    }

    /**
     * 删除数据
     * @param IDMustBePositiveInt $IDMustBePositiveInt
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function delete(IDMustBePositiveInt $IDMustBePositiveInt): \think\response\Json
    {
        $IDMustBePositiveInt->goCheck();
        $id = input('param.id');
        return $this->deleteDate((new AttributeModel()), $id);
    }
}